import requests
import json
from addict import Dict
from frame_work.util import (
    get_sql_info,
    check_tid,
    get_jid
)
from frame_work.setting import *
from frame_work.yaml_file import YAML
from frame_work.logger import Logger
from frame_work.login import PcLogin, AppLogin
from frame_work import menu_list
from frame_work.setting import image_Path


logger = Logger(__name__).get_logger()


class AppTask(object):

    # APP做增值任务
    def __init__(self, tid, uname):
        self.tid = tid
        self.uname = uname
        # self.domain = global_config.get_domain("domain")
        self.sign = self.get_session()
        try:
            self.value = get_jid(self.tid, self.uname)
            if not self.value:
                raise("无此参与记录")
        except BaseException:
            logger.debug("无此参与记录")
            return
        self.yaml = YAML(os.path.join(base_Dir, 'data', 'data.yaml'))

    def get_session(self):
        # 返回登录session
        login = AppLogin(self.uname)
        sign = login.appget_sign()
        return sign

    def get_task_type(self):
        """
        获取增值任务类型
        :return:
        """
        yaml_data = self.yaml.get_data('task_type')
        yaml_data.get('data').update({
            'uid': self.value[0].get("buyer_uid"),
            'sign': self.sign,
            'tid': self.tid
        })
        response = requests.get(url=yaml_data.get('url'), params=yaml_data.get('data'),
                                headers=yaml_data.get('header'))
        step_list = Dict(json.loads(response.text)).data.step
        task_type = []
        for step in step_list:
            if step.get('task_type'):
                task_type.append(step.get('task_type'))
        return task_type

    def app_task_request(self, type):
        """
        做增值任务
        :param type: 增值任务类型 # [2,,4,8,16,32,64,128]
        :return:
        """
        yaml_data = {}
        files = {}
        if type == '2':  # 验证店铺
            value = get_sql_info('select shop_name from sk_try where tid = %s', (self.tid,), meta={
                "info": "查询活动店铺名称"
            })
            yaml_data = self.yaml.get_data('task_verify_shop')
            yaml_data.get('data').update({
                'uid': self.value[0].get("buyer_uid"),
                'sign': self.sign,
                'jid': self.value[0].get("jid"),
                'task_type': type,
                'text': value[0].get('shop_name')
            })
        elif type == '8':  # 回答问题
            value = get_sql_info('select task_content from sk_join_task where task_type=8 and jid = %s', (self.value[0].get("jid"),), meta={
                "info": "查询增值任务回答问题答案"
            })
            yaml_data = self.yaml.get_data('task_answer')
            yaml_data.get('data').update({
                'uid': self.value[0].get("buyer_uid"),
                'sign': self.sign,
                'jid': self.value[0].get("jid"),
                'task_type': type,
                'text': json.loads(value[0].get('task_content').encode('utf-8').decode('unicode_escape')).get('a')
            })
            # print(json.loads(value[0].get('task_content').encode('utf-8').decode('unicode_escape')).get('a'))
        elif type in ('4', '16', '32', '64'):  # 推荐商品/收藏/关注/加入购物车
            yaml_data = self.yaml.get_data('task_other')
            yaml_data.get('data').update({
                'uid': self.value[0].get("buyer_uid"),
                'sign': self.sign,
                'jid': self.value[0].get("jid"),
                'task_type': type
            })
            files = {"file_name": ('filename', open(os.path.join(image_Path, '精品试用活动.png'), 'rb'), "image/png")}
        return requests.post(url=yaml_data.get(
            'url'), data=yaml_data.get('data'), files=files).text

    def quality_task(self, types):
        """
        app端做精品任务
        :param type:增值任务类型数组
        :return:
        """
        try:
            for task_type in types:
                if task_type == '128':  # 增值任务同店铺的2个链接不验证，跳过，提交任务的时候一起提交
                    continue
                result = self.app_task_request(task_type)
                if json.loads(result).get('code') in (
                        'OK', 'ERROR_EXCLUTED'):  # ERROR_EXCLUTED代表验证过了,也算
                    logger.info("增值任务类型:%s的上传验证成功" % task_type)
                else:
                    logger.debug(
                        "增值任务类型:%s的上传验证失败或者重复验证,无法继续执行提交任务操作" %
                        task_type)
                    raise("增值任务类型:%s的上传验证失败或者重复验证,无法继续执行提交任务操作" % task_type)
        except Exception as e:
            logger.debug("增值任务验证出现错误: %s" % e)
            return False
        else:  # 没有错误会被执行,代表所有增值任务验证都成功
            logger.info("所有增值任务验证成功")
            return True

    def app_submit_task(self):
        """
        提交增值任务
        :return:
        """
        task_type_list = self.get_task_type()
        if not self.quality_task(task_type_list):
            return
        yaml_data = self.yaml.get_data('submit_task')
        yaml_data.get('data').update({
            'uid': self.value[0].get("buyer_uid"),
            'sign': self.sign,
            'jid': self.value[0].get("jid")
        })
        if '128' in task_type_list:  # 如果有其它店铺链接增值任务，提交任务需要带上这个参数
            yaml_data.get('data').update(
                {"other_urls[0]": "https://detail.tmall.com/item.htm?id=633488188442&ali_refid=a3_430582_1006:1104380429:N:UcX6wzRNaVR6nvKsSGo/tA==:78fedabf8e66857a228c0a4c1a9a5a84&ali_trackid=1_78fedabf8e66857a228c0a4c1a9a5a84&spm=a230r.1.14.6&sku_properties=5919063:6536025;122216431:27772",
                 "other_urls[1]": "https://detail.tmall.com/item.htm?id=655701835188&ali_refid=a3_430582_1006:1123397704:N:KZa0QM+DyaDGbplyTh5jbA==:8a9b27ccd6f931efa21cb470fe99ba29&ali_trackid=1_8a9b27ccd6f931efa21cb470fe99ba29&spm=a230r.1.14.11&sku_properties=10004:7195672376;5919063:6536025"
                 })
        res = requests.post(url=yaml_data.get('url'), data=yaml_data.get('data'),
                            headers=yaml_data.get('header'))
        if json.loads(res.text).get('code') == 'OK':
            logger.info("提交任务成功")
        else:
            logger.info("提交任务失败:%s" % res.text)


def main():
    while True:
        # 选择功能菜单
        menu_list.quality_task_menu()
        # 选择
        choise = input("请输入您的选择: ")
        if choise in ('q', 'Q'):
            break
        try:
            tid = int(input(u'请输入活动tid: '))
            status = check_tid(tid)
            if not status:
                raise Exception("活动tid不存在try表，请核实后在重新输入")
        except Exception as e:
            logger.error("reszon => %s" % e)
        else:
            uname = input('请输入做增值任务试客名称:\n')
            task = AppTask(tid, uname)
            task.app_submit_task()


if __name__ == '__main__':
    main()
